/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-03-12 16:46:26
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-20 10:43:43
 * @Description: file content
 */
import { Service } from "egg";

export default class UserService extends Service {
  /** 根据用户id获取用户角色及权限列表 */
  async getUserPermissionById(uid: number | string = 0) {
    const role_ids = await this.getUserRoleIds(uid);
    const permList = await this.app.model.Sys.RolePermission.findAll({
      where: {
        role_id: role_ids,
        type: 0, //暂只获取菜单的权限列表
      },
    });
    // console.log(permList);
    return Array.from(new Set(permList.map((item) => item.perm_id)));
  }

  /**
   *获取用户的角色id列表
   *
   * @param {(number|string)} [userId=0] 用户uid 数据库主键
   * @return {Array} [] 角色id数组
   * @memberof UserService
   */
  async getUserRoleIds(userId: number | string = 0) {
    const userInfo = await this.ctx.model.Sys.User.findByPk(userId, {
      attributes: ["role_ids"],
    });
    return userInfo?.role_ids ? userInfo?.role_ids.split(",") : [];
  }
}
